﻿/**
 * 轮播图片管理组件
 * 使用方法：new LunBoTu(options)
 */
define(['jquery', 'upload', 'backend'], function ($, Upload, Backend) {
    
    var LunBoTu = function(options) {
        this.options = $.extend({
            containerId: 'slider-images-container',
            inputId: 'c-image', 
            addBtnId: 'add-image-group',
            countId: 'image-count',
            maxImages: 5,
            fieldName: 'image'
        }, options);
        
        this.images = [];
        this.imageCount = 0;
        this.init();
    };

    LunBoTu.prototype = {
        init: function() {
            this.container = $('#' + this.options.containerId);
            this.input = $('#' + this.options.inputId);
            this.addBtn = $('#' + this.options.addBtnId);
            this.countSpan = $('#' + this.options.countId);
            
            this.bindEvents();
            this.loadExistingImages();
        },

        bindEvents: function() {
            var self = this;
            
            // 添加图片按钮
            this.addBtn.on('click', function() {
                self.addImageGroup();
            });
            
            // 删除图片组
            $(document).on('click', '.remove-image-group', function() {
                var index = $(this).data('idx');
                self.removeImageGroup(index);
            });
            
            // 监听输入变化
            $(document).on('input', '.image-input', function() {
                self.updateImages();
            });
        },

        addImageGroup: function() {
            if (this.imageCount >= this.options.maxImages) {
                Backend.api.toastr.warning('最多只能添加' + this.options.maxImages + '张图片！');
                return;
            }
            
            var index = this.imageCount;
            var template = this.getImageGroupTemplate(index);
            this.container.append(template);
            
            this.imageCount++;
            this.updateCount();
            this.initUploadComponents();
        },

        removeImageGroup: function(index) {
            $('.slider-image-group[data-index="' + index + '"]').remove();
            this.reindexGroups();
            this.updateImages();
        },

        reindexGroups: function() {
            var self = this;
            this.imageCount = 0;
            
            this.container.find('.slider-image-group').each(function(newIndex) {
                $(this).attr('data-index', newIndex);
                $(this).find('.panel-title').html('<i class="fa fa-image"></i> 图片 ' + (newIndex + 1) + 
                    '<button type="button" class="btn btn-xs btn-danger pull-right remove-image-group" data-idx="' + newIndex + '" style="margin-top: -2px;">' +
                    '<i class="fa fa-trash"></i> 删除</button>');
                
                // 更新所有相关的ID和name
                $(this).find('input, button').each(function() {
                    var $this = $(this);
                    var name = $this.attr('name');
                    var id = $this.attr('id');
                    var dataInputId = $this.attr('data-input-id');
                    var dataPreviewId = $this.attr('data-preview-id');
                    
                    if (name) $this.attr('name', name.replace(/\[\d+\]/, '[' + newIndex + ']'));
                    if (id) $this.attr('id', id.replace(/-\d+/, '-' + newIndex));
                    if (dataInputId) $this.attr('data-input-id', dataInputId.replace(/-\d+/, '-' + newIndex));
                    if (dataPreviewId) $this.attr('data-preview-id', dataPreviewId.replace(/-\d+/, '-' + newIndex));
                });
                
                self.imageCount++;
            });
            
            this.updateCount();
        },

        getImageGroupTemplate: function(index, data) {
            data = data || {};
            return `
                <div class="slider-image-group panel panel-info slider-form-spacing" data-index="${index}" style="margin-bottom: 10px;">
                    <div class="panel-heading">
                        <h5 class="panel-title">
                            <i class="fa fa-image"></i> 图片 ${index + 1}
                            <button type="button" class="btn btn-xs btn-danger pull-right remove-image-group" 
                                    data-idx="${index}" style="margin-top: -2px;">
                                <i class="fa fa-trash"></i> 删除
                            </button>
                        </h5>
                    </div>
                    <div class="panel-body">
                        <div class="row">
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label class="control-label">预览:</label>
                                    <div>
                                        <img src="${data.url || '/assets/img/placeholder.png'}" 
                                             alt="预览" class="image-preview" data-idx="${index}"
                                             style="width:100%;max-width:120px;height:80px;object-fit:cover;border:1px solid #eee;">
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group" style="margin-bottom: 20px;">
                                    <label class="control-label">图片标题:</label>
                                    <input type="text" class="form-control image-input" 
                                           name="images[${index}][title]" 
                                           value="${data.title || ''}" 
                                           placeholder="请输入图片标题"
                                           style="margin-bottom: 10px;">
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group" style="margin-bottom: 20px;">
                                    <label class="control-label">图片链接:</label>
                                    <input type="text" class="form-control image-input" 
                                           name="images[${index}][href]" 
                                           value="${data.href || ''}" 
                                           placeholder="点击图片时跳转的链接"
                                           style="margin-bottom: 10px;">
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group" style="margin-bottom: 20px;">
                                    <label class="control-label">图片地址:</label>
                                    <div class="input-group">
                                        <input type="text" class="form-control image-input image-url-input" 
                                               name="images[${index}][url]" 
                                               id="carousel-img-${index}"
                                               value="${data.url || ''}" 
                                               placeholder="图片URL地址"
                                               style="margin-bottom: 10px;">
                                        <div class="input-group-btn">
                                            <button type="button" class="btn btn-danger plupload"  data-width="750" data-height="422"
                                                    data-input-id="carousel-img-${index}" data-mimetype="image/*" 
                                                    data-multiple="false" data-preview-id="p-carousel-${index}">
                                                <i class="fa fa-upload"></i>
                                            </button>
                                            <button type="button" class="btn btn-success ai-generate-image" 
                                                    data-type="carousel-${index}" data-input-id="carousel-img-${index}"
                                                     data-width="750" data-height="422"
                                                    data-say="生成一张适合轮播展示的图片，风格现代简洁">
                                                <i class="fa fa-magic"></i> AI
                                            </button>
                                        </div>
                                    </div>
                                    <ul class="row list-inline plupload-preview" id="p-carousel-${index}" 
                                        style="margin-top: 10px;"></ul>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            `;
        },

        loadExistingImages: function() {
            var value = this.input.val();
            
            // 添加更严格的数据验证
            if (value && 
                typeof value === 'string' && 
                value.trim() !== '' && 
                value !== 'undefined' && 
                value !== 'null') {
                try {
                    var data = JSON.parse(value);
                    if (Array.isArray(data) && data.length > 0) {
                        for (var i = 0; i < data.length; i++) {
                            if (data[i] && typeof data[i] === 'object') {
                                var template = this.getImageGroupTemplate(i, data[i]);
                                this.container.append(template);
                                this.imageCount++;
                            }
                        }
                        this.updateCount();
                        this.initUploadComponents();
                    } else {
                        // 没有有效数据时添加一个空的图片组
                        this.addImageGroup();
                    }
                } catch (e) {
                    // 解析失败时添加一个空的图片组
                    this.addImageGroup();
                }
            } else {
                // 没有数据时添加一个空的图片组
                this.addImageGroup();
            }
        },

        updateImages: function() {
            var images = [];
            var self = this;
            
            this.container.find('.slider-image-group').each(function() {
                var $group = $(this);
                var image = {
                    title: $group.find('input[name*="[title]"]').val() || '',
                    href: $group.find('input[name*="[href]"]').val() || '',
                    url: $group.find('input[name*="[url]"]').val() || ''
                };
                images.push(image);
                
                // 更新预览图片
                var $preview = $group.find('.image-preview');
                if (image.url) {
                    $preview.attr('src', image.url);
                }
            });
            
            this.input.val(JSON.stringify(images));
        },

        updateCount: function() {
            this.countSpan.text(this.imageCount);
            
            // 更新添加按钮状态
            if (this.imageCount >= this.options.maxImages) {
                this.addBtn.prop('disabled', true).addClass('disabled');
            } else {
                this.addBtn.prop('disabled', false).removeClass('disabled');
            }
        },

        initUploadComponents: function() {
            var self = this;
            
            // 初始化上传组件
            this.container.find('.plupload:not([initialized])').each(function() {
                debugger;
                var $btn = $(this);
                $btn.attr('initialized', 'true');
                
                // 绑定上传成功事件
                $btn.on('upload:success', function(e, data) {
                    var inputId = $btn.data('input-id');
                    $('#' + inputId).val(data.url).trigger('input');
                });
            });
            
            // 重新初始化FastAdmin上传组件
            if (typeof Upload !== 'undefined') {
                Upload.api.init();
            }
        }
    };

    return LunBoTu;
});